package com.webull.information.center.carwler.task;

import java.util.List;
import java.util.function.Consumer;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.webull.information.center.carwler.common.model.NewsInformation;
import com.webull.information.center.carwler.common.model.StockTitle;
import com.webull.information.center.carwler.common.util.news.BloombergTopNewsUitl;
import com.webull.information.center.carwler.common.util.news.BloombergTopNewsUitl.BloomergItem;
import com.webull.information.center.carwler.task.handler.StockBloombergNewsHandler;
import com.webull.information.center.carwler.task.support.TikcerNewsProcessor;
import com.webull.information.center.common.constants.Constants;
import com.webull.information.client.model.News;
import com.webull.information.client.model.parm.NewsRelType;
import com.webull.securities.client.model.Stock2Information;
import com.webull.securities.client.service.StockService;

@Component
public class News_Bloomberg_Stocks_Task {
    protected final Logger logger = LogManager.getLogger(getClass());
    //	private @Autowired @Qualifier("executor_news") ThreadPoolTaskExecutor threadPoolTaskExecutor;
    private @Autowired
    StockService stockService;
    private @Autowired
    StockBloombergNewsHandler stockBloombergNewsHandler;
    private final Integer pageSize = 100;

	private @Autowired TikcerNewsProcessor tikcerNewsProcessor;
	private @Autowired BloombergTopNewsUitl bloombergTopNewsUitl;
    /**
     * 全量扫描
     *
     * @since 0.1.0
     */
    public Integer stockFinanceNewsExchangeCode(String exchangeCode, String bbRegionAlias) {
        return stockFinanceNewsExchangeCode(exchangeCode, -1, null, bbRegionAlias);
    }

    public Integer stockFinanceNewsExchangeCode(String exchangeCode, Integer lastId, Integer loop,
                                                String bbRegionAlias) {
        logger.info(
                "News_Bloomberg_Stocks_Task.News_Bloomberg_Stocks_TaskExchangeCode start exchangeCode:{},lastId:{},loop:{}",
                exchangeCode, lastId, loop);
        int loop_ = 0;
        full:
        do {
            if (loop != null && loop > 0 && ++loop_ > loop) {
                break full;
            }
            List<Stock2Information> res = stockService.queryPagingInform(exchangeCode, lastId, pageSize);
            if (res == null || res.isEmpty()) {
                lastId = null;
                break full;
            }
            logger.info("News_Bloomberg_Stocks_Task.News_Bloomberg_Stocks_TaskExchangeCode stocks:" + res.size());
            lastId = res.get(res.size() - 1).getTickerId();
            procss(res, bbRegionAlias);
        } while (true);

        return lastId;
    }

    private void procss(List<Stock2Information> res, String bbRegionAlias) {
        try {
            if (res == null)
                return;

            final Consumer<Stock2Information> process = input -> {
                StockTitle stockTitle = new StockTitle();
                BeanUtils.copyProperties(input, stockTitle);
				stockTitle.setBbRegionAlias(bbRegionAlias);
				stockBloombergNewsHandler.handlerByStockTitle4Bloomerg(stockTitle);
                logger.info("News_Bloomberg_Stocks_Task.procss stockTitle:{},{}" + stockTitle, bbRegionAlias);
            };

            /**
             *
             * 改成单线程
             */
            for (Stock2Information information:res) {
                try {
                    process.accept(information);
                } catch (Exception e) {
                    logger.info("News_Bloomberg_Stocks_Task.procss",e);
                }
            }
// 		   News_TaskUtil.multiThreadProcess(res, process, threadPoolTaskExecutor);

            logger.info("News_Bloomberg_Stocks_TaskTask procss end:" + res.size());
        } catch (Exception e) {
            logger.error("News_Bloomberg_Stocks_TaskTask 全量新闻任务失败", e);
        }
    }

	public void handlerTopNews2() {
		final Consumer<List<BloomergItem>> processList = items0 -> {
			if (items0 != null)
				items0.forEach(vv -> {

					NewsInformation info0 = new NewsInformation();

					info0.setRegionId(0);
					info0.setLanguage(Constants.lang_en);
					info0.setArticleClass(NewsInformation.ArticleClass.articleEn);
					info0.setCollectSource(News.CollectSource.Bloomb);
					info0.setTitle(vv.getTitle());
					info0.setUrl(vv.getLink());
					info0.setNewsTime(vv.getNewsTime());
					info0.setSourceName("bloomberg.com");
					info0.addMainPic(vv.getPicutre());
					info0.setMainProxy(true);
					info0.setSiteType(News.SiteType.PIRORIT);
					// info0.setForceReview(true);
					info0.setHomePage(vv.getHome());
					if (News.HomeType.frontPage.equals(info0.getHomePage())) {
						info0.getMainPic().setThumSize(450);
					}
					logger.info("handlerTopNews bloomberg.com....title:{},url:{}", info0.getTitle(), info0.getUrl());
					tikcerNewsProcessor.bindTargetNewsRecord(info0, 1, NewsRelType.homePage);
				});
		};
		
		List<BloomergItem> topNewsList = bloombergTopNewsUitl.parseTopNewsList();

		processList.accept(topNewsList);
		logger.info("handlerTopNews reuters.parseNewsList end!!!");

	}
}
